<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of controller
 *
 * @author phamhphuc
 */

class referer_action_controller_admin extends system_controller_admin {
    public $permission = array();
    public function __construct($config) {
        parent::__construct($config);
        //force https login if it is not https
        if (($_SERVER['HTTPS'] != "on") && ($_SERVER['HTTP_HOST'] != "localhost")) {
            $url = "https://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
            header("Location: {$url}");
            exit;
        }

    }

    public function init() {
        parent::init();
        $url = "http://" . $_SERVER['HTTP_HOST'];
        $urls = explode("www/admin", $_SERVER['REQUEST_URI']);
        $url .= $urls[0] . "www/";

        $uid = $this->session->user['user_id'];
        $key = md5($this->config['secret_key'] . $uid);

        $this->view->iframe_url = $url . "?isliked=1&uid={$uid}&key={$key}";

        // get out permission list for current user
        $user = $this->_getCurrentUser();

        if($user['permission']) {
            $this->permission = unserialize($user['permission']);
        }
        $this->view->can_delete_user = $this->isAllow("delete_user");
        $this->view->can_create_user = $this->isAllow("create_user");
        $this->view->can_login_as_user = $this->isAllow("login_as_user");

    }
    /**
     *
     * @param String $permissionKey
     * @return Boolean
     */
    protected function isAllow($permissionKey){
        $user = $this->_getCurrentUser();
        if($user['group_id'] == 1) {
            return true;
        }
        if($user['group_id'] == 3){
            return false;
        }
        if(in_array($permissionKey, $this->permission)){
            return true;
        }
        return false;
    }

    public function indexAction()
    {
        // get appviews statistic
        $appviews = $this->getLast7DaysStatistic("#__statistic_appview");
        $this->view->appviews = $appviews;
        $contributions = $this->getLast7DaysStatistic("#__statistic_contributions");
        $this->view->contributions = $contributions;
    }
    
    public function editcalendarAction()
    {
        $sql = "select * from #__question_day where user_id = {$this->config['user_id']} order by day_num ASC";
        $this->view->days = $this->db->getRows($sql);
    }
    
    public function setupcalendarquestionAction()
    {                
        $questions = $this->db->getRows("select * from #__question_day where user_id = {$this->config['user_id']}");
        if(count($questions) > 0) {
            header("location: ?action=editcalendar");die;
        }
        $SQL = "
            INSERT INTO `#__question_day` (`question_day_id`, `day_num`, `question`, `answer_1`, `answer_2`, `answer_3`, `picture_url`, `question_label`, `user_id`) VALUES
            (NULL, 22, '', '', '', '', '', '', '{$this->config['user_id']}'),
            (NULL, 23, '', '', '', '', '', '', '{$this->config['user_id']}'),
            (NULL, 24, '', '', '', '', '', '', '{$this->config['user_id']}'),
            (NULL, 25, '', '', '', '', '', '', '{$this->config['user_id']}'),
            (NULL, 26, '', '', '', '', '', '', '{$this->config['user_id']}'),
            (NULL, 27, '', '', '', '', '', '', '{$this->config['user_id']}'),
            (NULL, 28, '', '', '', '', '', '', '{$this->config['user_id']}'),
            (NULL, 29, '', '', '', '', '', '', '{$this->config['user_id']}'),
            (NULL, 30, '', '', '', '', '', '', '{$this->config['user_id']}'),
            (NULL, 31, '', '', '', '', '', '', '{$this->config['user_id']}');
            ";
            $this->db->query($SQL);            
            header("location: ?action=editcalendar");die;
    }

    public function testcodeAction()
    {
        $secret = $this->_getParam("secret");
        require_once '../../../libs/PHPGangsta/GoogleAuthenticator.php';
        $ga = new PHPGangsta_GoogleAuthenticator();
        $oneCode = $ga->getCode($secret);
        echo $oneCode;die;
    }

    public function loginsecurityAction()
    {
        require_once '../../../libs/PHPGangsta/GoogleAuthenticator.php';
        $ga = new PHPGangsta_GoogleAuthenticator();

        $user = $this->_getCurrentUser(false);
        // get and check mfa secret
        $secretKey = $user['mfa_secret'];
        if(!$secretKey) {
            $secretKey = $ga->createSecret();
            $this->db->update("#__admin_user", array('mfa_secret' => $secretKey), "user_id = '{$this->config['user_id']}'");
        }

        if($this->_isPost()){
            if(isset($_POST['removelogin'])){
                $this->db->update("#__admin_user", array('is_2steps_login' => 0, "mfa_secret" => ""), "user_id = '{$this->config['user_id']}'");
                $user = $this->_getCurrentUser(false);
                $secretKey = $ga->createSecret();
                $this->db->update("#__admin_user", array('mfa_secret' => $secretKey), "user_id = '{$this->config['user_id']}'");
            } else {                                                            
                $oneCode = $ga->getCode($secretKey);
                $twoCode = $ga->getCode($secretKey, floor(time() / 30) - 1);
                $threeCode = $ga->getCode($secretKey, floor(time() / 30) + 1);
                if(($oneCode == $_POST['data']['code']) || ($twoCode == $_POST['data']['code']) || ($threeCode == $_POST['data']['code'])){
                    $this->db->update("#__admin_user", array('is_2steps_login' => 1), "user_id = '{$this->config['user_id']}'");
                    $user = $this->_getCurrentUser(false);
                } else {
                    $this->view->error = "The entered authentication code was not correct or out of sync. Please try again.";
                }
            }

        }
        $this->view->is2Steps = $user['is_2steps_login'];
        $qrCodeUrl = $ga->getQRCodeGoogleUrl("EasterCalendar_{$user['username']}", $secretKey);
        $this->view->qrCodeUrl = $qrCodeUrl;
        $this->view->secretKey = $secretKey;

    }

    public function getLast7DaysStatistic($tableName){
        $limitTime = time() - (7 * 24 * 60 * 60); // 7 days ago
        $limitTime = mktime(0, 0, 0, date("m", $limitTime), date("d", $limitTime), date("Y", $limitTime));
        $SQL = "
            SELECT count( * ) AS totalrecords, DAY( FROM_UNIXTIME( date_time ) ) AS day_num, date_time
            FROM {$tableName}
            WHERE date_time >= {$limitTime} and client_id = {$this->config['user_id']}
            GROUP BY day_num
            ORDER BY date_time ASC
            ";
        $data = $this->db->getRows($SQL);

        // fill in number 0 for empty day
        $returnData = array();
        $item = null;
        $isMatch = false;
        $limitT = time() - (7 * 24 * 60 * 60);
        for($i = 0;$i<=7;$i++) {
            $t = $limitT + $i * 24 * 60 * 60;
            $day = date("d", $t);
            // get out the day if it have in array
            foreach($data as $d) {
                if($d['day_num'] == $day) {
                    $item = $d;
                    $isMatch = true;
                    break;
                }
            }
            if($isMatch) {
                $isMatch = false;
                $returnData[] = $item;
            } else {
                $returnData[] = array(
                    'totalrecords' => 0,
                    'day_num' => $day,
                    'date_time' => $t
                );
            }
        }
        return $returnData;
    }
    /**
     * @return system_mail
     */
    protected function _getEmailObject()
    {
        require '../../../libs/system_mail.php';
        $mail = new system_mail();
        return $mail;
    }

    public function loginAction()
    {
        if($this->_isLogined()) {
            header("location: ?action=index");die;
        }
        if(isset($_POST['data'])){
            $data = $_POST['data'];
            $sql = "select * from #__admin_user where username = '{$data['username']}' and password = md5('{$data['password']}')";
            $user = $this->db->getRow($sql);
            if($user) {

                if($user['is_2steps_login']){
                    $this->session->verifyuser = $user;
                    header("location: ?action=login&verify");die;
                } else {
                    $this->session->user = $user;
                    $this->session->verifyuser = false;
                    $this->db->update("#__admin_user", array(
                        "last_login" => time(),
                        "last_ip" => $_SERVER['REMOTE_ADDR']
                    ),"username = '{$user['username']}'");
                    header("location: ?action=index");die;
                }
            } else {
                $this->view->error = "Wrong username or password entered. Please try again";
            }
        } elseif(isset($_POST['verificationcode'])) {
            $user = $this->session->verifyuser;
            if(!$user){
                header("location: ?action=login");die;
            }
            require_once '../../../libs/PHPGangsta/GoogleAuthenticator.php';
            $ga = new PHPGangsta_GoogleAuthenticator();
            $oneCode = $ga->getCode($user['mfa_secret']);
            $twoCode = $ga->getCode($user['mfa_secret'], floor(time() / 30) - 1);
            $threeCode = $ga->getCode($user['mfa_secret'], floor(time() / 30) + 1);
            if(($oneCode == $_POST['verificationcode']) || ($twoCode == $_POST['verificationcode']) || ($threeCode == $_POST['verificationcode'])) {
                $this->session->user = $user;
                $this->session->verifyuser = false;
                $this->db->update("#__admin_user", array(
                    "last_login" => time(),
                    "last_ip" => $_SERVER['REMOTE_ADDR']
                ),"username = '{$user['username']}'");
                header("location: ?action=index");die;
            } else {
                $this->view->error = "Wrong code";
            }
        } elseif(isset($_POST['type']) && ($_POST['type'] == "lostpassword")) {
            $username = $_POST['username'];
            if(!$username){
                $this->view->error = "Please enter your username";
            } else {
                // search user with user like this
                $username = mysql_escape_string($username);
                $resetuser = $this->db->getRow("select * from #__admin_user where username = '{$username}'");
                if($resetuser) {
                    // build reset key
                    $resetkey = md5($this->config['secret_key'] . $resetuser['last_login']);
                    // build reset URL
                    $url = "http://" . $_SERVER['HTTP_HOST'];
                    $urls = explode("www/admin", $_SERVER['REQUEST_URI']);
                    $url .= $urls[0] . "www/admin/?action=login&username={$username}&type=resetpassword&resetkey={$resetkey}";

                    $langcode = "en";
                    if(isset($resetuser['langcode'])){
                        $langcode = $resetuser['langcode'];
                    }
                    $search = array("[url]", "[name]");
                    $replace = array($url, $resetuser['name']);

                    $emaildata = include "../../../emailtemplates/{$langcode}/forgot_password.php";
                    $emaildata['body_html'] = str_replace($search, $replace, $emaildata['body_html']);

                    $emailObj = $this->_getEmailObject();
                    $emailObj->SetFrom($emaildata['sender_email'], $emaildata['sender_name']);
                    $emailObj->AddAddress($resetuser['email'], $resetuser['name']);
                    $emailObj->Subject = $emaildata['subject'];
                    $emailObj->MsgHTML($emaildata['body_html']);
                    if($emaildata['cc']){
                        $emailObj->AddCC($emaildata['cc']);
                    }
                    if($emaildata['bcc']){
                        $emailObj->AddBCC($emaildata['cc']);
                    }
                    $emailObj->Send();
                }
            }
        } elseif(isset($_POST['type']) && ($_POST['type'] == "resetpassword")){
            $username = mysql_escape_string($_POST['username']);
            $resetkey = mysql_escape_string($_POST['resetkey']);
            $password = mysql_escape_string($_POST['password']);
            if($username & $resetkey & $password){
                $resetuser = $this->db->getRow("select * from #__admin_user where username = '{$username}'");
                if(!$resetuser){
                    $this->view->error = "This user is not exists";
                } else {
                    $newresetkey = md5($this->config['secret_key'] . $resetuser['last_login']);
                    if($resetkey == $newresetkey) {
                        $this->db->update("#__admin_user", array('password' => md5($password)), "username = '{$username}'");
                        header("location: ?action=login&info=Your new password is saved");die;
                    } else {
                        $this->view->error = "Session is not valid, please try a another reset URL.";
                    }
                }
            } else {
                $this->view->error = "Please enter your new password";
            }
        }

        if($this->config['template_name'] == 'iadmin') {
            $this->setlayout("login");
        }

    }

    public function signupAction()
    {
        $error = "";
        $tmppass = "";

        if($this->_isLogined()) {
            header("location: ?action=index");die;
        }
        if(isset($_POST['data'])){
            $user = $_POST['data'];
            $tmppass = $user['password'];
            $olduserusername = $this->db->getRow("select * from #__admin_user where username = '{$user['username']}'");
            if($olduserusername){
                $error = "Username is existed";
            }
            $olduseremail = $this->db->getRow("select * from #__admin_user where email = '{$user['email']}'");
            if($olduseremail){
                $error = "Email is existed";
            }

            if(!$user['tos']){
                $error = "Please accept our terms of services";
            }

            if($error == "") {
                // add more data for this user
                $currentTime = time();
                $user['created_time'] = $currentTime;
                $user['expired_time'] = $currentTime + 60 * 60 * 24 * $this->config['number_of_trial_days'];
                $user['ip'] = $_SERVER['REMOTE_ADDR'];

                unset ($user['retypepassword']);
                unset ($user['tos']);
                // add new user to database
                $user['password'] = md5($user['password']);
                $userid = $this->db->insert("#__admin_user", $user);
                if($userid){
                    header("location: ?action=login&issuccess=1&username={$user['username']}");die;
                } else {
                    $error = "System error: Can't create new user";
                    $user['password'] = $tmppass;
                    $user['retypepassword'] = $tmppass;
                    $this->view->data = $user;
                }
            } else {
                $user['password'] = $tmppass;
                $user['retypepassword'] = $tmppass;
                $this->view->data = $user;
            }
        }

        if($this->config['template_name'] == 'iadmin') {
            $this->setlayout("login");
        }
        $this->view->error = $error;
    }

    public function manageuserAction()
    {
        $user = $this->_getCurrentUser();
        if($user['group_id'] > 2){
            $this->_redirect("index");
        }
        $sql = "select * from #__admin_user where is_deleted = 0";
        // if it is sale guy
        if($user['group_id'] == 2){
            $sql = "select * from #__admin_user where created_by_id = '{$user['user_id']}' and is_deleted = 0";
        }

        // get list of created user
        $createdUsersResult = $this->db->getRows("select user_id, username from #__admin_user where group_id <= 2");
        $saleUsers = array();
        $saleUsers[0] = array("user_id" => 0, "username" => "");
        foreach($createdUsersResult as $k => $v) {
            $saleUsers[$v['user_id']] = $v;
        }
        $this->view->saleUsers = $saleUsers;
        $this->view->users = $this->db->getRows($sql);
    }

    public function _redirect($actionName){
        header("location: ?action={$actionName}");die;
    }

    public function userdeleteAction()
    {
        $this->_checkAndRedirect("delete_user","manageuser");
        if(isset($_GET['user_id'])) {
            $data = array(
                'is_deleted' => 1,
                'is_disabled' => 1,
                'expired_time' => 0
            );
            $this->db->update("#__admin_user",$data, "user_id = " . mysql_escape_string($_GET['user_id']));
            header("location: ?action=manageuser&issuccess=1");die;
        }
    }

    public function loginasuserAction()
    {
        $this->_checkAndRedirect("login_as_user","manageuser");

        $uid = $this->_getParam("user_id", false);

        if(!$this->checkUserOwner($uid)){
            $this->_redirect("manageuser");
        }

        $user = $this->_getCurrentUser();
        if(($user['group_id'] < 3) && $uid) {

            $this->session->adminuser = $this->session->user;

            $sql = "select * from #__admin_user where user_id = '{$uid}'";

            $newuser = $this->db->getRow($sql);

            $this->session->user = $newuser;
        }
        header("location: ?action=index");
        die;
    }

    public function leveldeleteAction()
    {
        if(isset($_GET['level_id'])) {
            $this->db->delete("#__level", "level_id = " . mysql_escape_string($_GET['level_id']));
            $this->updateUserLevel($_GET['user_id']);
            header("location: ?action=userlevel&user_id={$_GET['user_id']}&issuccess=1");die;
        }
        header("location: ?action=manageuser");die;
    }
    
    public function invoicedeleteAction()
    {
        if(isset($_GET['invoice_id'])) {
            $this->db->delete("#__invoice", "invoice_id = " . mysql_escape_string($_GET['invoice_id']));            
            header("location: ?action=userinvoice&user_id={$_GET['user_id']}&issuccess=1");die;
        }
        header("location: ?action=manageuser");die;
    }
    
    public function userinvoiceAction()
    {
        //check uid and validate
        $uid = $this->_getParam("user_id", false);
        if(!$uid || !$this->checkUserOwner($uid)) {
            header("location: ?action=manageuser");die;
        }                
        
        // get out user data
        $user = $this->db->getRow("select * from #__admin_user where user_id = '{$uid}'");
        $this->view->userdata = $user;
        
        if($this->_isPost()){
            $data = $this->_getParam("data", false);                
            $data['period_start'] = $this->_parseDate($data['period_start']);
            $data['period_end'] = $this->_parseDate($data['period_end']);
            $data['user_id'] = $_POST['user_id'];
            $data['created_by'] = $this->config['user_id'];
            $data['last_update'] = time();
            if(strtotime($data['period_start']) >= strtotime($data['period_end'])) {
                $this->view->error = "The start date can not be greater then the end date";
            } else {
                $this->db->insert("#__invoice", $data);
            }            
            $this->view->data = $data;
        }
        
        // get invoice list for current user
        $invoices = $this->db->getRows("select * from #__invoice where user_id = {$uid}");
        $this->view->invoices = $invoices;
    }
    
    private function _parseDate($dateString){
        $dates = explode(".", $dateString);
        return "{$dates[2]}-{$dates[1]}-{$dates[0]}";
    }

    public function userlevelAction(){

        $levels = include '../level.php';
        $this->view->levels = $levels;

        if(isset($_REQUEST['user_id'])){
            $uid = mysql_escape_string($_REQUEST['user_id']);
            if(!$this->checkUserOwner($uid)){
                header("location: ?action=manageuser");die;
            }

            if(count($_POST) > 0) {
                $levelselectkey = $_POST['user']['levelselect'];
                $levelselect = false;
                // search level detail in selection
                foreach($levels as $l) {
                    if($l['key'] == $levelselectkey) {
                        $levelselect = $l;
                    }
                }
                if($levelselect) {
                    // select the last level what is applied for current user
                    $lastLevel = $this->db->getRow("select * from #__level where user_id = '{$uid}' order by level_id DESC");
                    $startDate = date("Y-m-d");
                    if($lastLevel){
                        $startFrom = (strtotime($lastLevel['end_date']) + 24 * 60 * 60);
                        if($startFrom < time()){
                            $startFrom = time();
                        }
                        $startDate = date("Y-m-d", $startFrom);
                    }

                    $endDate = date("Y-m-d", strtotime($startDate) + $levelselect['period'] * 24 * 60 * 60);

                    $levelrecord = array(
                        'user_id' => $uid,
                        'level_key' => $levelselect['key'],
                        'level_name' => $levelselect['name'],
                        'start_date' => $startDate,
                        'end_date' => $endDate,
                        'created_by_id' => $this->config['user_id'],
                        'update_time' => time(),
                        'access_type' => $levelselect['access_type']
                    );

                    $this->db->insert("#__level", $levelrecord);
                    $this->updateUserLevel($uid);
                }
            }

            $user = $this->db->getRow("select * from #__admin_user where user_id = '{$uid}'");
            $this->view->userdata = $user;
            // get list of levels of current user
            $this->view->userlevels = $this->db->getRows("select * from #__level where user_id = '{$uid}' order by level_id DESC");
            // get list of created user
            $createdUsersResult = $this->db->getRows("select user_id, username from #__admin_user where user_id <= 2");
            $saleUsers = array();
            $saleUsers[0] = array("user_id" => 0, "username" => "");
            foreach($createdUsersResult as $k => $v) {
                $saleUsers[$v['user_id']] = $v;
            }
            $this->view->saleUsers = $saleUsers;


        } else {
            header("location: ?action=manageuser");die;
        }
    }

    public function userpermissionAction()
    {
        // get list of all permissions
        $permissions = include 'permission.php';
        $permissionlist = array();

        if(isset($_REQUEST['user_id'])){
            $uid = mysql_escape_string($_REQUEST['user_id']);
            if(!$this->checkUserOwner($uid)){
                header("location: ?action=manageuser");die;
            }

            if(count($_POST) > 0) {
                $newpermission = $_POST['permission'];
                $savepermission = array();
                foreach($newpermission as $k => $v) {
                    $savepermission[] = $k;
                }
                $savepermission = serialize($savepermission);
                $this->db->update("#__admin_user", array('permission' => $savepermission), "user_id = '{$uid}'");
            }

            $user = $this->db->getRow("select * from #__admin_user where user_id = '{$uid}'");
            $user['password'] = "";
            $user['extra_user_data'] = unserialize($user['extra_user_data']);
            $user['permission'] = @unserialize($user['permission']);
            $this->view->userdata = $user;

            //build permission rules
            foreach($permissions as $k => $p) {
                $item = array(
                        'key' => $k,
                        'name' => $p,
                        'is_allowed' => false
                    );
                if($user['permission']) {
                    if(in_array($k, $user['permission'])) {
                        $item['is_allowed'] = true;
                    }
                }
                $permissionlist[] = $item;
            }
        } else {
            header("location: ?action=manageuser");die;
        }
        $this->view->permissionlist = $permissionlist;
    }

    protected function _checkAndRedirect($permissionKey, $action) {
        if(!$this->isAllow($permissionKey)){
            header("location: ?action={$action}");die;
        }
    }

    public function createnewuserAction()
    {

        $this->_checkAndRedirect("create_user","manageuser");

        $error = "";
        $tmppass = "";
        if(count($_POST) > 0){
            $user = $_POST['user'];
            $tmppass = $user['password'];
            $user['password'] = md5($user['password']);

            if(isset($_POST['user_id'])) {
                if(!$this->checkUserOwner($_POST['user_id'])){
                    header("location: ?action=manageuser");die;
                }

                $olduserusername = $this->db->getRow("select * from #__admin_user where username = '{$user['username']}' and user_id <> {$_POST['user_id']}");
                if($olduserusername){
                    $error = "Username is existed";
                }
                $olduseremail = $this->db->getRow("select * from #__admin_user where email = '{$user['email']}' and user_id <> {$_POST['user_id']}");
                if($olduseremail){
                    $error = "Email is existed";
                }
                if($_POST['user']['password'] == "") {
                    unset($user['password']);
                }
                if($error == ""){
                    $user['extra_user_data'] = serialize($user['extra_user_data']);

                    if($this->session->user['group_id'] != 1) {
                        unset($user['group_id']);
                    }

                    $this->db->update("#__admin_user", $user, "user_id = " . mysql_escape_string($_POST['user_id']));
                    header("location: ?action=manageuser&issuccess=1");die;
                } else {
                    $user['password'] = $tmppass;
                    $user['extra_user_data'] = unserialize($user['extra_user_data']);
                    $this->view->userdata = $user;
                }
            } else {
                $olduserusername = $this->db->getRow("select * from #__admin_user where username = '{$user['username']}'");
                if($olduserusername){
                    $error = "Username is existed";
                }
                $olduseremail = $this->db->getRow("select * from #__admin_user where email = '{$user['email']}'");
                if($olduseremail){
                    $error = "Email is existed";
                }
                if($error == "") {
                    // add more data for this user
                    $currentTime = time();
                    $user['created_time'] = $currentTime;
                    $user['expired_time'] = time();//$currentTime + 60 * 60 * 24 * $this->config['number_of_trial_days'];
                    $user['ip'] = $_SERVER['REMOTE_ADDR'];
                    $user['is_disabled'] = 1;
                    $user['created_by_id'] = $this->config['user_id'];
                    $user['extra_user_data'] = serialize($user['extra_user_data']);
                    // add new user to database
                    if($this->session->user['group_id'] != 1) {
                        unset($user['group_id']);
                    }
                    $userid = $this->db->insert("#__admin_user", $user);

                    // send email to new user
                    if(isset($_POST['notifytouser']) && ($_POST['notifytouser'] == "on")) {
                        $urls = explode("users/www", $_SERVER['REQUEST_URI']);
                        $loginURL = "http://{$_SERVER['HTTP_HOST']}{$urls[0]}admin";

                        $search = array(
                            "[name]","[username]","[email]","[password]","[url]"
                        );
                        $replace = array(
                            $user['name'],$user['username'],$user['email'], $_POST['user']['password'],$loginURL
                        );

                        // get email template
                        $langcode = "en";
                        if(isset($user['langcode'])){
                            $langcode = $user['langcode'];
                        }
                        $emaildata = include "../../../emailtemplates/{$langcode}/new_account_confirm.php";
                        $emaildata['body_html'] = str_replace($search, $replace, $emaildata['body_html']);

                        $emailObj = $this->_getEmailObject();
                        $emailObj->SetFrom($emaildata['sender_email'], $emaildata['sender_name']);
                        $emailObj->AddAddress($user['email'], $user['name']);
                        $emailObj->Subject = $emaildata['subject'];
                        $emailObj->MsgHTML($emaildata['body_html']);
                        if($emaildata['cc']){
                            $emailObj->AddCC($emaildata['cc']);
                        }
                        if($emaildata['bcc']){
                            $emailObj->AddBCC($emaildata['cc']);
                        }
                        $emailObj->Send();
                    }

                    if($userid){
                        header("location: ?action=manageuser&issuccess=1");die;
                    } else {
                        $error = "System error: Can't create new user";
                        $user['password'] = $tmppass;
                        $user['extra_user_data'] = unserialize($user['extra_user_data']);
                        $this->view->userdata = $user;
                    }
                } else {
                    $user['password'] = $tmppass;
                    $user['extra_user_data'] = @unserialize($user['extra_user_data']);
                    $this->view->userdata = $user;
                }
            }
        } else {
            if(isset($_GET['user_id'])){
                if(!$this->checkUserOwner($_GET['user_id'])){
                    header("location: ?action=manageuser");die;
                }
                $user = $this->db->getRow("select * from #__admin_user where user_id = '{$_GET['user_id']}'");
                $user['password'] = "";
                $user['extra_user_data'] = unserialize($user['extra_user_data']);
                $this->view->userdata = $user;
            }
        }
        $this->view->error = $error;
    }

    public function checkUserOwner($userID) {
        $user = $this->_getCurrentUser();
        if($user['group_id'] == 1){
            return true;
        }

        if($userID == $this->config['user_id']){
            return true;
        }

        $sql = "select * from #__admin_user where user_id = '{$userID}' and created_by_id = '{$user['user_id']}'";
        return $this->db->getRow($sql);
    }

    public function toolsAction()
    {
        if(isset($_POST['childaction']) && ($_POST['childaction'] == "updateglobalsetting")){
            $data = $_POST['data'];
            foreach($data as $k => $v) {
                $this->updateSettingForAllUsers($k, $v);
            }
        }
    }

    public function statisticAction()
    {
        $whereStr = "";
        $whereStr2 = "";
        $uid = @$_GET['uid'];
        if($uid) {
            $whereStr = " where client_id = {$uid}";
            $whereStr2 = " where user_id = {$uid}";
        }
        $this->view->contribution_number = $this->db->getOne("select count(*) as total from #__answer{$whereStr2}");
        $this->view->app_views = $this->db->getOne("select count(*) as total from #__statistic_appview{$whereStr}");
        $this->view->dooropen_views = $this->db->getOne("select count(*) as total from #__statistic_dooropen{$whereStr}");
        $this->view->like_number = $this->db->getOne("select count(*) as total from #__statistic_like{$whereStr}");
        $this->view->tos_clicks = $this->db->getOne("select count(*) as total from #__statistic_tosclick{$whereStr}");
        $this->view->user_number = $this->db->getOne("select count(*) as total from #__admin_user");
        // get list of all users
        $sql = "select * from #__admin_user order by username ASC";
        $this->view->users = $this->db->getRows($sql);

    }
    /**
     *
     * @return file_uploader_server
     */
    public function getFileUploader()
    {
        require '../../../libs/file_uploader_server.php';
        $fileuploader = new file_uploader_server($this->config);
        return $fileuploader;
    }    

    public function deleteimgAction()
    {
        $user = $this->_getCurrentUser();
        $settingKey = $this->_getParam("settingkey", false);
        $imgkey = $this->_getParam("imgkey", false);
        $fileuploader = $this->getFileUploader();
        if($settingKey == "frontendsetup"){
            if($imgkey && isset($this->frontendsetup[$imgkey])){
                $fileuploader->deleteImgFile($this->frontendsetup[$imgkey]);
                $this->frontendsetup[$imgkey] = "";
                $this->db->update("#__admin_user", array("frontend_setup" => serialize($this->frontendsetup)), "user_id = {$user['user_id']}");
            }
        } else if($settingKey == "setting"){
            if($imgkey && isset($this->settings[$imgkey])){
                $fileuploader->deleteImgFile($this->settings[$imgkey]);
                $this->settings[$imgkey] = "";
                $this->db->update("#__admin_user", array("general_setting" => serialize($this->settings)), "user_id = {$user['user_id']}");
            }
        }
        die("done");
    }

    public function frontendsetupAction() {
        $fileuploader = $this->getFileUploader();
        if ($this->_isPost()) {
            $frontendsetup = $this->_filterTextArr($_POST['data'], array('contest_intro_text','text_below_contest'));

            if($frontendsetup['main_content_to_show_youtube'] != "") {
                if(strpos($frontendsetup['main_content_to_show_youtube'], "?")) {
                    $arrs = explode("?", $frontendsetup['main_content_to_show_youtube']);
                    parse_str($arrs[1], $vposts);
                    $frontendsetup['main_content_to_show_youtube'] = "http://www.youtube.com/v/" . $vposts['v'];
                } elseif(strpos($frontendsetup['main_content_to_show_youtube'], "youtu.be")) {
                    $arrs = explode("youtu.be/", $frontendsetup['main_content_to_show_youtube']);
                    $frontendsetup['main_content_to_show_youtube'] = "http://www.youtube.com/v/" . $arrs[1];
                }
            }

            if (count($_FILES) > 0) {
                if (isset($_FILES['template_banner_img_url'])) {
                    $bannerresult = $fileuploader->handleuploadfile($_FILES['template_banner_img_url'], 810, $this->frontendsetup['template_banner_img_url']);
                    $frontendsetup['template_banner_img_url'] = ($bannerresult['fileurl'] ? $bannerresult['fileurl'] : $this->frontendsetup['template_banner_img_url']);
                    if($fileuploader->handledeletefile('template_banner_img_url', $this->frontendsetup['template_banner_img_url'])){
                        $frontendsetup['template_banner_img_url'] = false;
                    }
                }
            }
            $user = $this->_getCurrentUser();
            $frontendsetup = array_merge($this->frontendsetup, $frontendsetup);

            $this->db->update("#__admin_user", array("frontend_setup" => serialize($frontendsetup)), "user_id = {$user['user_id']}");

            // update template config for template select
//            $this->settings['template_name'] = $frontendsetup['select_template'];
//            $this->db->update("#__admin_user", array("general_setting" => serialize($this->settings)), "user_id = {$user['user_id']}");

            $this->reloadSettings();
            $this->view->frontendsetup = $frontendsetup;
        }
    }

    public function generalsettingAction()
    {
        if($this->_isPost()){
            $settings = $this->_filterTextArr($_POST['data'], array('terms_of_service', 'footer_center_text'));
            if(count($_FILES) > 0){
                $fileuploader = $this->getFileUploader();
                if(isset($_FILES['logo_img_url'])){
                    $logofileresult = $fileuploader->handleuploadfile($_FILES['logo_img_url'], 300, $this->settings['logo_img_url']);
                    $settings['logo_img_url'] = ($logofileresult['fileurl']?$logofileresult['fileurl']:$this->settings['logo_img_url']);
                    if($fileuploader->handledeletefile('logo_img_url', $this->settings['logo_img_url'])){
                        $settings['logo_img_url'] = false;
                    }
                }
                if(isset($_FILES['turn_off_img_url'])){
                    $turnofffileresult = $fileuploader->handleuploadfile($_FILES['turn_off_img_url'], 810, $this->settings['turn_off_img_url']);
                    $settings['turn_off_img_url'] = ($turnofffileresult['fileurl']?$turnofffileresult['fileurl']:$this->settings['turn_off_img_url']);
                    if($fileuploader->handledeletefile('turn_off_img_url', $this->settings['turn_off_img_url'])){
                        $settings['turn_off_img_url'] = false;
                    }
                }

                if(isset($_FILES['facebook_share_image_url'])){
                    $turnofffileresult = $fileuploader->handleuploadfile($_FILES['facebook_share_image_url'], 300, $this->settings['facebook_share_image_url']);
                    $settings['facebook_share_image_url'] = ($turnofffileresult['fileurl']?$turnofffileresult['fileurl']:$this->settings['facebook_share_image_url']);
                    if($fileuploader->handledeletefile('facebook_share_image_url', $this->settings['facebook_share_image_url'])){
                        $settings['facebook_share_image_url'] = false;
                    }
                }

                if(isset($_FILES['facebook_like_image_url'])){
                    $turnofffileresult = $fileuploader->handleuploadfile($_FILES['facebook_like_image_url'], 300, $this->settings['facebook_like_image_url']);
                    $settings['facebook_like_image_url'] = ($turnofffileresult['fileurl']?$turnofffileresult['fileurl']:$this->settings['facebook_like_image_url']);
                    if($fileuploader->handledeletefile('facebook_like_image_url', $this->settings['facebook_like_image_url'])){
                        $settings['facebook_like_image_url'] = false;
                    }
                }

                if(isset($_FILES['like_gate_img_url'])){
                    $turnofffileresult = $fileuploader->handleuploadfile($_FILES['like_gate_img_url'], 810, $this->settings['like_gate_img_url']);
                    $settings['like_gate_img_url'] = ($turnofffileresult['fileurl']?$turnofffileresult['fileurl']:$this->settings['like_gate_img_url']);
                    if($fileuploader->handledeletefile('like_gate_img_url', $this->settings['like_gate_img_url'])){
                        $settings['like_gate_img_url'] = false;
                    }
                }
            }
            // end of upload files
            // save data
            $user = $this->_getCurrentUser();
            $this->db->update("#__admin_user", array("general_setting" => serialize($settings)), "user_id = {$user['user_id']}");
            $this->reloadSettings();
            $this->view->settings = $this->settings;

        }
    }

    public function apppublishAction()
    {
        if(isset($_GET['tabs_added'])){
            foreach($_GET['tabs_added'] as $pageID => $v) {
                $this->db->update("#__admin_user", array('fb_page_id' => $pageID, ), "user_id = {$this->session->user['user_id']}");
                // update page data for offline save
                $pageData = file_get_contents("https://graph.facebook.com/{$pageID}");
                $pageData = (array)json_decode($pageData);
                $this->db->update("#__admin_user", array('fb_page_data' => serialize($pageData) ), "user_id = {$this->session->user['user_id']}");
            }
            $this->_reloadUserData();
            header("location: ?action=apppublish");die;
        }
        // update session user
        // build direct URL
        $url = "http://" . $_SERVER['HTTP_HOST'];
        $urls = explode("www/admin", $_SERVER['REQUEST_URI']);
        $url .= $urls[0] . "www/";
//        $this->view->iframe_url = $url . "?isliked=1&uid=" . $this->session->user['user_id'];
        $this->view->tab_receive_url = $url . "admin/?action=apppublish";

    }



    private function _reloadUserData()
    {
        // update session user
        $this->session->user = $this->_getCurrentUser(false);
        $this->view->user = $this->session->user;
    }

    public function languagesettingAction()
    {
        $lang = $this->_getParam("lang", "no");

        if($this->_isPost()){
            $postLang = $this->_filterTextArr($_POST['data']);
            $user = $this->_getCurrentUser();
            if($user['langs'] != "") {
                $userlangs = unserialize($user['langs']);
            }
            $userlangs[$lang] = $postLang;
            $this->db->update("#__admin_user", array("langs" => serialize($userlangs)), "user_id = {$user['user_id']}");
            $this->_reloadUserData();
        }

        $userlangs = false;
        $user = $this->_getCurrentUser();
        if($user['langs'] != "") {
            $userlangs = unserialize($user['langs']);
        }
        // load languages
        $langs = include "../../../lang/{$lang}.php";
        // load language file if exists
        if(isset($userlangs[$lang])){
            $newlangs = $userlangs[$lang];
            $langs = array_merge($langs, $newlangs);
        }

        $this->view->langs = $langs;
        $this->view->lang = $lang;
    }

    public function exportcsvAction(){
        $filter = $this->_getParam("filter", "all");
        $whereStr = "";
        if($filter != "all") {
            $limitTime = 0;
            switch($filter){
                case "today":
                    $limitTime = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
                    $whereStr = " and update_time > {$limitTime}";
                    break;
                case "yesterday":
                    $limitTime1 = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
                    $limitTime2 = $limitTime1 - (24 * 60 * 60);
                    $whereStr = " and update_time < {$limitTime1} and update_time > {$limitTime2}";
                    break;
                case "thisweek":
                    $limitTime = strtotime('Last Monday', time());
                    $whereStr = " and update_time > {$limitTime}";
                    break;
                case "lastweek":
                    $limitTime1 = strtotime('Last Monday', time());
                    $limitTime2 = $limitTime1 - (7 * 24 * 60 * 60);
                    $whereStr = " and update_time < {$limitTime1} and update_time > {$limitTime2}";
                    break;
                case "thismonth":
                    $limitTime = mktime(0, 0, 0, date("m"), 1, date("Y"));
                    $whereStr = " and update_time > {$limitTime}";
                    break;
                case "lastmonth":
                    $t = strtotime("-1 month");
                    $limitTime1 = mktime(23,59,59, date("m", $t), date("t", $t), date("Y", $t));
                    $limitTime2 = mktime(0,0,0, date("m", $t), 1, date("Y", $t));
                    $whereStr = " and update_time < {$limitTime1} and update_time > {$limitTime2}";
                    break;
            }

        }

        $sql = "select * from #__answer where user_id = {$this->config['user_id']} {$whereStr} order by update_time DESC";

        $answers = $this->db->getRows($sql);
//        echo "<pre>";print_r($answers);die;
        // set up parser data
        $exportData = array();
        $exportData[] = array(
            'ID', 'Name', 'Email', 'IP', "Date/time", "Newsletter"
        );

        foreach($answers as $c) {            
            $newslettertext = "Yes";
            if($c['is_newsletter'] != "on"){
                $newslettertext = "No";
            }
            $exportData[] = array(
                $c['answer_id'], $c['name'], @$c['email'], $c['ip'], date("d.m.Y H.i", $c['update_time']),$newslettertext
            );
        }

        require_once '../../../libs/parsecsv/parsecsv.lib.php';
        $parser = new parseCSV();
        $parser->output (true, date('d.m.Y H.i') . "-{$filter}-eastercalendar-results.csv", $exportData);
        die;
    }
    public function exportcsvuserAction()
    {
        $user = $this->_getCurrentUser();
        if($user['group_id'] > 2){
            $this->_redirect("index");
        }
        $sql = "select * from #__admin_user";
        // if it is sale guy
        if($user['group_id'] == 2){
            $sql = "select * from #__admin_user where created_by_id = '{$user['user_id']}'";
        }

        // get list of created user
        $createdUsersResult = $this->db->getRows("select user_id, username from #__admin_user where user_id <= 2");
        $saleUsers = array();
        $saleUsers[0] = array("user_id" => 0, "username" => "");
        foreach($createdUsersResult as $k => $v) {
            $saleUsers[$v['user_id']] = $v;
        }
        $users = $this->db->getRows($sql);
        $exportData = array();
        $exportData[] = array(
            'UID', 'Name','Username', 'Email', 'Last login', 'Group', 'IP', 'Last IP', "Created by","Company name", "Phone number", "zipcode", "city", "country"
        );
        foreach($users as $u) {
            $extra = unserialize($u['extra_user_data']);
            $exportData[] = array(
                $u['user_id'], $u['name'], $u['username'],$u['email'], date("d.m.Y H:i",$u['last_login']),$this->config['groups'][$u['group_id']],$u['ip'],$u['last_ip'], $saleUsers[$u['user_id']]['username'], @$extra['company_name'], @$extra['phone_number'],@$extra['zipcode'],@$extra['city'],@$extra['country'],
            );
        }
        require_once '../../../libs/parsecsv/parsecsv.lib.php';
        $parser = new parseCSV();         
        $parser->output (true, date('d.m.Y H.i') . "-eastercalendar-users.csv", $exportData);
        die;
    }
    public function getwinnerAction()
    {
        $this->_setNoLayout();
        $sql = "select * from #__answer where user_id = {$this->config['user_id']} order by rand() limit 0, 1";
        $aid = $this->_getParam("aid", false);
        if($aid){
            $sql = "select * from #__answer where answer_id = {$aid}";
        }

        $winner = $this->db->getRow($sql);
        if($winner){
            // get question detail for winner
            $question = $this->db->getRow("select * from #__question_day where question_day_id = '{$winner['question_day_id']}'");
            $winner['question'] = $question;
        }
       $this->view->winner = $winner;

    }

    public function deletealldataAction(){
        $this->db->delete("#__answer", "user_id = {$this->config['user_id']}");
        die("done");
    }

    public function deletedupplicateddataAction()
    {
        $total = 0;
        $sqlSelectDupplicated = "
            select * from #__answer where answer_id not in
            (
            SELECT min(answer_id) as answer_id FROM #__answer where user_id = '{$this->config['user_id']}' group by `email`
            ) and user_id = '{$this->config['user_id']}'
            ";
        $rows = $this->db->getRows($sqlSelectDupplicated);
        if($rows){
            foreach($rows as $r) {
                $this->db->delete("#__answer", "answer_id = {$r['answer_id']}");
            }
            $total = count($rows);
        }
        echo $total;die;
    }

    public function viewresultsAction()
    {
        $currentPage = 1;
        $start = 0;

        if(isset($_GET['p'])){
            $currentPage = intval($_GET['p']);
            if($currentPage <= 0){
                $currentPage = 1;
            }
        }

        $day = @$_GET['day'];
        if(!$day){
            $day = "*";
        }

        $whereString = "";
        $whereStringAnd = "";
        if($day != "*"){
            $whereString = " where day_num = {$day} ";
            $whereStringAnd = " and day_num = {$day} ";
        }

        $total = $this->db->getOne("select count(*) as total from #__answer where user_id = {$this->config['user_id']} {$whereStringAnd}");
        $limit = $this->config['facebooktab_item_per_page'];
        if($total > 2000) {
            $limit = 50;
        }
        $start = ($currentPage - 1) * $limit;

        $sql = "select * from
        (
            select a.* , q.question, q.answer_1, q.answer_2, q.answer_3 from #__answer a, #__question_day q where a.question_day_id = q.question_day_id and q.user_id = {$this->config['user_id']}
        ) aw
        {$whereString} order by update_time DESC limit {$start},{$limit}";

        $comments = $this->db->getRows($sql);
        $numOfPages = ceil($total/$limit);
        // calculate start and end page
        $startpage = 1;
        $endpage = 6;
        $prePage = 1;
        $nextPage = 6;
        if($currentPage > 3) {
            $startpage = $currentPage - 3;
        }
        if($currentPage > 1){
            $prePage = $currentPage - 1;
        }
        $endpage = $startpage + 7;
        if($endpage > $numOfPages){
            $endpage = $numOfPages;
        }
        $nextPage = $currentPage + 1;
        if($nextPage > $numOfPages) {
            $nextPage = $numOfPages;
        }
        $this->view->startpage = $startpage;
        $this->view->endpage = $endpage;
        $this->view->prePage = $prePage;
        $this->view->nextPage = $nextPage;

        $this->view->comments = $comments;
        $this->view->total = $total;
        $this->view->currentPage = $currentPage;
        $this->view->numOfPages = $numOfPages;
        $this->view->day = $day;
    }

    public function reportingAction()
    {
        $currentPage = 1;
        $start = 0;

        $filter = $this->_getParam("filter", "all");
        $whereStr = "";
        if($filter != "all") {
            $limitTime = 0;
            switch($filter){
                case "today":
                    $limitTime = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
                    $whereStr = " and update_time > {$limitTime}";
                    break;
                case "yesterday":
                    $limitTime1 = mktime(0, 0, 0, date("m"), date("d"), date("Y"));
                    $limitTime2 = $limitTime1 - (24 * 60 * 60);
                    $whereStr = " and update_time < {$limitTime1} and update_time > {$limitTime2}";
                    break;
                case "thisweek":
                    $limitTime = strtotime('Last Monday', time());
                    $whereStr = " and update_time > {$limitTime}";
                    break;
                case "lastweek":
                    $limitTime1 = strtotime('Last Monday', time());
                    $limitTime2 = $limitTime1 - (7 * 24 * 60 * 60);
                    $whereStr = " and update_time < {$limitTime1} and update_time > {$limitTime2}";
                    break;
                case "thismonth":
                    $limitTime = mktime(0, 0, 0, date("m"), 1, date("Y"));
                    $whereStr = " and update_time > {$limitTime}";
                    break;
                case "lastmonth":
                    $t = strtotime("-1 month");
                    $limitTime1 = mktime(23,59,59, date("m", $t), date("t", $t), date("Y", $t));
                    $limitTime2 = mktime(0,0,0, date("m", $t), 1, date("Y", $t));
                    $whereStr = " and update_time < {$limitTime1} and update_time > {$limitTime2}";
                    break;
            }

        }

        $total = $this->db->getOne("select count(*) as total from #__answer where user_id = {$this->config['user_id']} {$whereStr}");
        $limit = 2000;
        if($total > 2000) {
            $limit = 50;
        }
        $start = ($currentPage - 1) * $limit;

        $sql = "select * from #__answer where user_id = {$this->config['user_id']} {$whereStr} order by update_time DESC limit {$start},{$limit}";

        $answers = $this->db->getRows($sql);

        $numOfPages = ceil($total/$limit);
        // calculate start and end page
        $startpage = 1;
        $endpage = 6;
        $prePage = 1;
        $nextPage = 6;
        if($currentPage > 3) {
            $startpage = $currentPage - 3;
        }
        if($currentPage > 1){
            $prePage = $currentPage - 1;
        }
        $endpage = $startpage + 7;
        if($endpage > $numOfPages){
            $endpage = $numOfPages;
        }
        $nextPage = $currentPage + 1;
        if($nextPage > $numOfPages) {
            $nextPage = $numOfPages;
        }
        $this->view->startpage = $startpage;
        $this->view->endpage = $endpage;
        $this->view->prePage = $prePage;
        $this->view->nextPage = $nextPage;

        $this->view->answers = $answers;
        $this->view->total = $total;
        $this->view->currentPage = $currentPage;
        $this->view->numOfPages = $numOfPages;
        $this->view->filter = $filter;
    }

    public function logoutAction()
    {
        $this->session->user = false;
        if($this->session->adminuser) {

            $this->session->user = $this->session->adminuser;
            $this->session->adminuser = false;
            header("location: ?action=manageuser");
            die;
        }
        header("location: ?action=login");die;
    }

    public function myaccountAction()
    {
        if(count($_POST)){
            $data = $_POST['data'];
            if($data['password'] == $data['retypepassword']){
                $user = array(
                  'password' => md5($data['password'])
                );
                $this->db->update("#__admin_user", $user, "user_id = {$this->config['user_id']}");
                $this->logoutAction();
            }
        }
    }
    
    public function updatecalendarAction()
    {
        if(count($_POST) > 0) {
            $data = $_POST['data'];
            foreach($data as $k => $v) {
                $this->db->update("#__question_day", $v, "question_day_id = {$k} and user_id = {$this->config['user_id']}");
            }
            echo 1;die;
        }
        echo 0;die;
    }

    public function editcalendarpictureAction()
    {
        $questionDayID = @$_REQUEST['question_day_id'];
        $questionSQL = "select * from #__question_day where question_day_id = {$questionDayID}";
        $question = $this->db->getRow($questionSQL);
        $this->view->question = $question;
        $error = "";
        if($this->_isPost()){
            $fileuploader = $this->getFileUploader();
            if(isset($_FILES['picturefile'])){
                $logofileresult = $fileuploader->handleuploadfile($_FILES['picturefile'], 360, $question['picture_url']);
                $question['picture_url'] = ($logofileresult['fileurl']?$logofileresult['fileurl']:$question['picture_url']);
            }
            $this->db->update("#__question_day", array(
            'picture_url' => $question['picture_url']
            ), "question_day_id = {$questionDayID}");
        }
        
//        if(count($_FILES) > 0 && $_FILES['picturefile']['name'] != ""){
//            $target_path = "../uploads/";
//
//            $target_path = $target_path . time() . "_" . basename( $_FILES['picturefile']['name']);
//            $savePath = "uploads/" . time() . "_" . basename( $_FILES['picturefile']['name']);
//
//            if(move_uploaded_file($_FILES['picturefile']['tmp_name'], $target_path)) {
//
//                // resize and override image
//               require_once '../../../libs/SimpleImage.php';
//               $image = new SimpleImage();
//               $image->load($target_path);
//               $w = $image->getWidth();
//               $h = $image->getHeight();
//
//               if($w >= 360){
//                    $newH = ceil(360 * $h / $w);
//                    $image->resize(360,$newH);
//                    $image->save($target_path);
//               }
//
//                $this->db->update("#__question_day", array(
//                    'picture_url' => $savePath
//                    ), "question_day_id = {$questionDayID}");
//            } else{
//                $error = "There was an error uploading the file, please try again!";
//            }
//        }

        if(count($_POST) > 0) {
            if(strpos($_POST['video_url'], "?")) {
                $arrs = explode("?", $_POST['video_url']);
                parse_str($arrs[1], $vposts);
                $_POST['video_url'] = "http://www.youtube.com/v/" . $vposts['v'];
            } elseif(strpos($_POST['video_url'], "youtu.be")) {
                $arrs = explode("youtu.be/", $_POST['video_url']);
                $_POST['video_url'] = "http://www.youtube.com/v/" . $arrs[1];
            }
            $this->db->update("#__question_day", array(
                    'media_type' => $_POST['media_type'],
                    'video_url' => $_POST['video_url'],
                    'image_link' => $_POST['image_link']
                    ), "question_day_id = {$questionDayID}");

            header("location: ?action=editcalendar");die;
        }

        $this->view->error = $error;
    }

    private function _isLogined()
    {
        if($this->session->user) {
            return true;
        } else {
            return false;
        }
    }

    private function _getCurrentUser($useCache = true)
    {
        if(!$useCache) {
            $user = $this->session->user;
            $sql = "select * from #__admin_user where user_id = {$user['user_id']}";
            $this->session->user = $this->db->getRow($sql);
        }
        return $this->session->user;

    }

    private function _getFacebookObject()
    {
        require_once '../../../libs/facebook/facebook.php';
        $facebook = new Facebook(array(
          'appId'  => $this->config['facebook_app_id'],
          'secret' => $this->config['facebook_app_secret'],
          'fileUpload' => true
        ));
        return $facebook;
    }

    protected function _getParam($key, $defaultvalue = false) {
        if(isset($_REQUEST[$key])){
            return $_REQUEST[$key];
        } else {
            return $defaultvalue;
        }
    }

    protected function _isPost()
    {
        if(count($_POST) > 0) {
            return true;
        }
        return false;
    }
}

?>
